package com.nomito.minimito.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.nomito.minimito.entity.ImGroupEntity;
import com.nomito.minimito.entity.ImGroupfriendEntity;
import com.nomito.minimito.service.ImGroupService;
import com.nomito.minimito.service.ImGroupfriendService;
import com.nomito.minimito.vo.ActivityFootprintVo;
import com.nomito.minimito.vo.ActivityVo;
import com.nomito.minimito.vo.ActivitySearchParamVo;
import com.nomito.minimito.vo.CreateActivityVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nomito.minimito.common.utils.PageUtils;
import com.nomito.minimito.common.utils.Query;

import com.nomito.minimito.dao.SqActivityDao;
import com.nomito.minimito.entity.SqActivityEntity;
import com.nomito.minimito.service.SqActivityService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("sqActivityService")
public class SqActivityServiceImpl extends ServiceImpl<SqActivityDao, SqActivityEntity> implements SqActivityService {

    @Autowired
    private ImGroupService groupService;

    @Autowired
    private ImGroupfriendService groupfriendService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SqActivityEntity> page = this.page(
                new Query<SqActivityEntity>().getPage(params),
                new QueryWrapper<SqActivityEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public boolean createActivityAndGroup(CreateActivityVo vo) {
        //TODO 时间戳，用来当做群聊id(单体唯一，分布式不行，后期需要进行更改)
//        long GroupAccout = System.currentTimeMillis();
        //TODO 会出现一种情况，创建活动成功，但是创建群聊失败，发生的可能性不低，后续需要进行接口升级
        //1.首先保存活动信息，创建活动
        //1.1new一个持久化存储对象
        SqActivityEntity activityEntity = new SqActivityEntity();
        //1.2拷贝相同的属性值
        BeanUtils.copyProperties(vo,activityEntity);
        //1.3补充剩下的属性值，其中id需要复用，所以得收到生成
        long activityId = IdWorker.getId(activityEntity);
        activityEntity.setId(activityId);
        activityEntity.setTotalCount(vo.getFemaleCount()+vo.getMaleCount());
        //1.4保存
        boolean b = this.save(activityEntity);
        //2.创建临时聊天室
        ImGroupEntity groupEntity = new ImGroupEntity();
        groupEntity.setId(activityId);
        groupEntity.setLeaderId(vo.getInitiatorId());
        groupEntity.setGroupImage(vo.getImages());
        groupEntity.setGroupName(vo.getTitle());
        groupEntity.setDescription(vo.getTags());
        groupService.save(groupEntity);
        //3.为群组添加成员关系
        ImGroupfriendEntity groupfriendEntity = new ImGroupfriendEntity();
        groupfriendEntity.setGroupId(activityId);
        groupfriendEntity.setUserId(vo.getInitiatorId());
        groupfriendService.save(groupfriendEntity);
        return true;
    }

    /**
     * 活动筛选（聚合筛选）不传东西就是查询全部活动列表
     *          分页查询的参数
     *           adornParams({
     *             'page': this.pageIndex当前页码
     *             'limit': this.pageSize该页数量
     *             'key': this.dataForm.key搜索表单里的值
     *           })
     *           ActivitySearchParamVo里的参数
     */
    @Override
    public PageUtils complexQueryActivities(Map<String, Object> params, ActivitySearchParamVo vo) {
        QueryWrapper<SqActivityEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.like("title",key)
                    .or().like("address",key)
                    .or().like("tags",key);

            if (!StringUtils.isEmpty(vo.getBeginSort())){
                if (vo.getBeginSort()==1){
                    wrapper.orderByAsc("begin_time");
                }else wrapper.orderByDesc("begin_time");
            }
            if (!StringUtils.isEmpty(vo.getHotScore())){
                if (vo.getBeginSort()==1){
                    wrapper.orderByAsc("total_count");
                }else wrapper.orderByDesc("total_count");
            }
            if (vo.getHumanCount()!=null){
                String[] humancount = vo.getHumanCount().split("_");
                if (humancount.length == 2) {
                    wrapper.between("total_count",humancount[0],humancount[1]);
                }else {
                    if (humancount[0] == null) wrapper.le("total_count",humancount[1]);
                    else wrapper.ge("total_count",humancount[0]);
                }
            }
            if (!StringUtils.isEmpty(vo.getStatus())){
                wrapper.eq("activity_status",vo.getStatus());
            }
            if (vo.getCity()!=null){
                wrapper.eq("local_city",vo.getCity());
            }
            if (vo.getDetailAddress()!=null){
                wrapper.eq("local_detail",vo.getDetailAddress());
            }

        }


        wrapper.select("id","title","images","begin_time","end_time","address","male_count","female_count","total_count","tags","activity_status","add_content");
        IPage<SqActivityEntity> page = this.page(
                new Query<SqActivityEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public ActivityVo queryActivityInfo(Long activityId) {

//        ActivityVo activityVo = new ActivityVo();
//        SqActivityEntity sqActivityEntity = baseMapper.selectById(activityId);
//        BeanUtils.copyProperties(sqActivityEntity,activityVo);
//        return activityVo;
        return baseMapper.queryActivityInfo(activityId);

    }

    @Override
    public List<ActivityFootprintVo> queryJoinedActivity(Long userId) {
        return baseMapper.queryJoinedActivity(userId);
    }


}